from farstyle.filters import FilterBase

from django.conf import settings

import os
import warnings
import tempfile

BINARY = getattr(settings, 'CSSTIDY_BINARY', 'csstidy')
ARGUMENTS = getattr(settings, 'CSSTIDY_ARGUMENTS', '--template=highest')

warnings.simplefilter('ignore', RuntimeWarning)

class CSSTidyFilter(FilterBase):
    def filter_css(self, css):
        in_file = tempfile.NamedTemporaryFile(mode='w+b')
        in_file.write(css)
        
        out_file = tempfile.NamedTemporaryFile(mode='w+b')
        
        command = '%s %s %s %s' % (BINARY, in_file.name, ARGUMENTS, out_file.name)
        
        command_output = os.popen(command).read()
        
        filtered_css = out_file.read()
        out_file.close()
        in_file.close()
        
        #if self.verbose:
        #    print command_output
        
        return filtered_css
